package dto

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	validator "github.com/go-playground/validator/v10"
	enTranslations "github.com/go-playground/validator/v10/translations/en"
	zhTranslations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"regexp"
	"strings"
)

// https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Cross_Field_Validation

/*
{
    "msg": {
        "Login.user": "user为必填字段"
    }
}
变成
{
    "msg": {
        "user": "user为必填字段"
    }
}
*/

func RemoveTopStruct(fields map[string]string) map[string]string {
	rsp := map[string]string{}
	for key, val := range fields {
		index := strings.Index(key, ".")
		newKey := key[index+1:]
		rsp[newKey] = val
	}
	return rsp
}

// 自定义手机号码校验

// 初始化表单验证
func initTrans(locale string) (trans ut.Translator, err error) {
	if validate, ok := binding.Validator.Engine().(*validator.Validate); ok {
		// 注册翻译器，多语言
		enTranslator := en.New()
		zhTranslator := zh.New()
		uni := ut.New(enTranslator, zhTranslator) // 参数一：备用环境，后面参数：当前使用
		trans, ok = uni.GetTranslator(locale)
		if !ok {
			return nil, fmt.Errorf("uni.GetTranslator(%s)", locale)
		}
		if locale == "en" {
			err = enTranslations.RegisterDefaultTranslations(validate, trans)
			if err != nil {
				return nil, err
			}
		} else if locale == "zh" {
			err = zhTranslations.RegisterDefaultTranslations(validate, trans)
			if err != nil {
				return nil, err
			}
		} else {
			err = enTranslations.RegisterDefaultTranslations(validate, trans)
			if err != nil {
				return nil, err
			}
		}

		// 注册获取json的tag的自定义方法
		// https://github.com/go-playground/validator/blob/master/_examples/struct-level/main.go
		// 参考源码 37 行
		validate.RegisterTagNameFunc(func(field reflect.StructField) string {
			name := strings.SplitN(field.Tag.Get("json"), ",", 2)[0]
			if name == "-" { // json内的一种分割
				return ""
			}
			return name
		})

		// 注册手机号验证
		// https://github.com/go-playground/validator/blob/master/_examples/custom-validation/main.go
		// 参考源码 20 行
		_ = validate.RegisterValidation("mobile", func(fl validator.FieldLevel) bool {
			// 拿到mobile字段的值
			mobile := fl.Field().String()
			// 使用正则表达式判断
			reg := `^1([38][0-9]|14[579]|5[^4]|16[6]|7[1-35-8]|9[189])\d{8}$`
			var res = regexp.MustCompile(reg).MatchString(mobile)
			return res
		})
		// 注册自定义错误提醒
		// https://github.com/go-playground/validator/blob/master/_examples/translations/main.go
		// 105 行
		validate.RegisterTranslation("mobile", trans, func(ut ut.Translator) error {
			return ut.Add("mobile", "{0} 不是合法的手机号码!", true) // see universal-translator for details
		}, func(ut ut.Translator, fe validator.FieldError) string {
			t, _ := ut.T("mobile", fe.Field())
			return t
		})

		return trans, nil
	}
	return nil, errors.New("binding.Validator.Engine()")
}

// Trans 暴露全局变量
var Trans ut.Translator

// init 初始化表单验证
func init() {
	trans, err := initTrans("zh")
	if err != nil {
		panic(err)
	}
	Trans = trans
}
